package com.yj.auto.core.web.system.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yj.auto.Constants;
import com.yj.auto.core.base.annotation.Service;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.jfinal.base.BaseCache;
import com.yj.auto.core.jfinal.base.BaseService;
import com.yj.auto.core.web.system.model.Dict;

/**
 * Dict 管理 描述：
 */
@Service(name = "dictSrv")
public class DictService extends BaseService<Dict> implements BaseCache {

	private static final Log logger = Log.getLog(DictService.class);

	public static final String SQL_LIST = "system.dict.list";

	public static final Dict dao = new Dict().dao();

	@Override
	public Dict getDao() {
		return dao;
	}

	@Override
	public SqlPara getListSqlPara(QueryModel query) {
		if (StrKit.isBlank(query.getOrderby())) {
			query.setOrderby("sort");
		}
		return getSqlPara(SQL_LIST, query);
	}

	public List<Dict> children(Integer id, String state, String type) {
		if (null == id)
			id = new Integer(0);
		QueryModel query = new QueryModel();
		query.setId(id);
		query.setType(type);
		query.setState(state);
		query.setOrderby("sort");
		return find(SQL_LIST, query);
	}

	public List<Dict> children(Integer id, String state) {
		return children(id, state, null);
	}

	public List<Dict> children(String code, String state) {
		QueryModel query = new QueryModel();
		query.set("parent_val", code);
		query.setState(state);
		query.setOrderby("sort");
		return find(SQL_LIST, query);
	}

	public boolean updateSort(Integer[] id) {
		if (null == id || id.length < 1)
			return false;
		List<Dict> list = new ArrayList<Dict>();
		for (int i = 0; i < id.length; i++) {
			Dict d = new Dict();
			d.setId(id[i]);
			d.setSort(i + 1);
			list.add(d);
		}
		String sql = "update t_sys_dict set sort=? where id=?";
		int[] result = Db.batch(sql, "sort, id", list, 500);
		return result.length > 0;
	}

	@Override
	public void loadCache() {
		List<Dict> root = children(Constants.TREE_ROOT_ID, null);
		for (Dict r : root) {
			String key = r.getVal();
			List<Dict> vals = children(r.getId(), null);
			this.addCache(key, vals);
		}
	}

	@Override
	public String getCacheName() {
		return Constants.CACHE_NAME_DICT;
	}
}